package com.uchedao.vehicledetection.view.condition;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;

import com.nostra13.universalimageloader.utils.L;
import com.uchedao.vehicledetection.R;
import com.uchedao.vehicledetection.activity.ImagePagerActivity;
import com.uchedao.vehicledetection.adapter.GuiseAdapter;
import com.uchedao.vehicledetection.db.DbHelper;
import com.uchedao.vehicledetection.global.GlobalInfo;
import com.uchedao.vehicledetection.inf.IOnResultBack;
import com.uchedao.vehicledetection.loadstate.UCheDaoRelativeLayout;
import com.uchedao.vehicledetection.model.Condition;
import com.uchedao.vehicledetection.model.Draft;
import com.uchedao.vehicledetection.model.ResultIntArrayPics;
import com.uchedao.vehicledetection.utils.Util;
import com.uchedao.vehicledetection.view.widget.stickylistheaders.StickyListHeadersListView;

import java.io.File;
import java.util.ArrayList;

/**
 * Description:内饰检测view
 * <p/>
 * Date: 2015-09-16  10:07
 * User: wushan
 */
public class ConditionInteriorView extends UCheDaoRelativeLayout implements GuiseAdapter.GuiseAdapterListener,IOnResultBack{
    public static final int FROM_CAMERA = 701;// 拍照获取

    public static final int FROM_PICTURE = 702;// 从图库获取

    public static final int FROM_PIC_VIEWPAGER = 703;// 从图片浏览返回

    private ResultIntArrayPics tmpItem;

    private Condition condition;

    private GuiseAdapter interiorAdapter;

    private String tmpPath;// 临时图片路径

    private AlertDialog pickerDialog;// 图片选取对话框

    public ConditionInteriorView(Context context) {
        super(context);
    }

    public ConditionInteriorView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ConditionInteriorView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }


    @Override
    public boolean save() {

        ContentValues values = new ContentValues();
        values.put(DbHelper.KEY_DRAFT_CONDITION, toJson(condition));

        int status = condition.getStatus();
        values.put(DbHelper.KEY_DRAFT_CONDITION_STATUS, status);

        // 若VIN值为空
        if (TextUtils.isEmpty(condition.config_info.vin))
            condition.config_info.vin = GlobalInfo.draft.car_vin;

            // 如果VIN值有更改
        else if (!condition.config_info.vin.equals(GlobalInfo.draft.car_vin)) {
            values.put(DbHelper.KEY_DRAFT_CAR_VIN, condition.config_info.vin);
        }

        // int status = GlobalInfo.draft.status[Draft.TYPE_CONDITION];
        // // 若原先状态为未完成，且数据已变动，则状态改变为已完成
        // if (GlobalInfo.draft.status[Draft.TYPE_CONDITION] !=
        // Draft.STATUE_FINISH) {
        // values.put(DbHelper.KEY_DRAFT_CONDITION_STATUS, Draft.STATUE_FINISH);
        // status = Draft.STATUE_FINISH;
        // }

        // 保存成功
        if (GlobalInfo.dbHelper.updateDraf(GlobalInfo.draft.car_plate, values)) {
            GlobalInfo.draft.condition = condition.clone();
            GlobalInfo.draft.car_vin = condition.config_info.vin;
            GlobalInfo.draft.status[Draft.TYPE_CONDITION] = status;
            L.i(toJson(GlobalInfo.draft.condition));
            return true;
        }

        return false;
    }

    @Override
    public boolean dataChanged() {
//       L.i(toJson(condition));
//        L.i(toJson(GlobalInfo.draft.condition));
        return !toJson(condition).equals(toJson(GlobalInfo.draft.condition));
//        return false;
    }

    @Override
    public void initView() {
        LayoutInflater.from(mContext).inflate(R.layout.view_detection, this);
        StickyListHeadersListView stickListHeadersListView = (StickyListHeadersListView) findViewById(R.id.detection_listView);
//        interiorAdapter = new DetectionAdapter(mContext, getInteriorData(), this);
        interiorAdapter = new GuiseAdapter(mContext, getGuiseData(), this, GlobalInfo.resources.getStringArray(R.array.interior_select_values));
        stickListHeadersListView.setAdapter(interiorAdapter);
    }

    @Override
    public void initDataBeforView() {
//        if (GlobalInfo.draft == null) {
//            GlobalInfo.draft = new Draft();
//        }
        condition = GlobalInfo.draft.condition.clone();
    }

    @Override
    public void initDataAfterView() {

    }

    @Override
    public void initListener() {

    }

    /**
     * 内饰检测数据
     *
     * @return
     */
    private ResultIntArrayPics[] getGuiseData() {

        ResultIntArrayPics[] items = condition.interior;

        String[] headers = GlobalInfo.resources.getStringArray(R.array.interior_tabspec_entries);
        int[] arrayId = {R.array.interior_front_entries, R.array.interior_back_entries, R.array.interior_other_entries};
        String[] texts = Util.concat(GlobalInfo.resources.getStringArray(arrayId[0]), GlobalInfo.resources.getStringArray(arrayId[1]), GlobalInfo.resources.getStringArray(arrayId[2]));
        for (int i = 0; i < texts.length; i++) {
            if (items[i] == null)
                items[i] = new ResultIntArrayPics();

            if (i < 21) {
                items[i].header = headers[0];
            } else if (i >= 21 && i < 32) {
                items[i].header = headers[1];
            } else {
                items[i].header = headers[2];
            }

            items[i].name = texts[i];
            if (items[i].result == null) {
                items[i].result = new ArrayList<Integer>();
            }
            if (items[i].result.size() == 0)
                items[i].result.add(0);
        }
        return items;
    }

//    private ArrayList<Detection> getInteriorData() {
//        ArrayList<Detection> array = new ArrayList<Detection>();
//
//        String[] headers = GlobalInfo.resources.getStringArray(R.array.interior_tabspec_entries);
//
//        int[] arrayId = {R.array.interior_front_entries, R.array.interior_back_entries, R.array.interior_other_entries};
//        Detection detection = null;
//
//        for (int i = 0, k = 0; i < headers.length; i++) {
//            String[] texts = GlobalInfo.resources.getStringArray(arrayId[i]);
//            for (String text : texts) {
//                if (condition.interior[k] == null)
//                    condition.interior[k] = new ResultIntArrayPics();
//                condition.interior[k].name = text;
//                if (condition.interior[k].result == null) {
//                    condition.interior[k].result = new ArrayList<Integer>();
//                }
//                if (condition.interior[k].result.size() == 0)
//                    condition.interior[k].result.add(0);
//
//                detection = new Detection(Detection.TYPE_MULTIPLE);
//                detection.setHeader(headers[i]);
//                detection.setText(text);
//                detection.setRequestFocus(true);
//                detection.setResId(R.array.interior_select_values);
//                detection.setValues(condition.interior[k].result);
//                array.add(detection);
//                k++;
//            }
//        }
//        return array;
//    }

    /**
     * 显示图片选取对话框
     */
    public void showPickerDialog() {
        if (pickerDialog == null) {
            CharSequence[] items = {"拍照", "从图片库选择"};
            pickerDialog = new AlertDialog.Builder(mContext).setTitle("选择")
                    .setItems(items, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            if (which == 0) {
                                Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                                File file = new File(GlobalInfo.PIC_PATH, System.currentTimeMillis() + ".jpg");
                                tmpPath = file.getAbsolutePath();
                                Uri uri = Uri.fromFile(file);
                                i.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                                ((Activity) mContext).startActivityForResult(i, FROM_CAMERA);

                            } else {

                                Intent intent = new Intent();
                                /* 开启Pictures画面Type设定为image */
                                intent.setType("image/*");
                                /* 使用Intent.ACTION_GET_CONTENT这个Action */
                                // intent.setAction(Intent.ACTION_GET_CONTENT);
                                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                                    intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                                } else {
                                    intent.setAction(Intent.ACTION_GET_CONTENT);
                                }
                                /* 取得相片后返回本画面 */
                                ((Activity) mContext).startActivityForResult(intent, FROM_PICTURE);
                            }
                        }
                    }).create();
        }
        pickerDialog.show();

    }

    @Override
    public void onPhotoAdd(ResultIntArrayPics item) {
        tmpItem = item;
        showPickerDialog();
    }

    @Override
    public void onPhotoEdit(ResultIntArrayPics item) {
        tmpItem = item;
        // 图片浏览软件
        Intent intent = new Intent(mContext, ImagePagerActivity.class);
        intent.putExtra("title", item.name);
        intent.putStringArrayListExtra("pic_path_list", item.pic_path_list);

        if (mContext instanceof Activity) {
            Activity activity = (Activity) mContext;
            activity.startActivityForResult(intent, FROM_PIC_VIEWPAGER);
        }

    }

    public void onActivityResultView(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case FROM_CAMERA:// 相机
                    tmpItem.pic_path_list.add(tmpPath);
                    // guiseAdapter.notifyDataSetChanged();
                    break;

                case FROM_PICTURE:// 图库
                    Uri uri = data.getData();
                    tmpPath = Util.getPath(mContext, uri);
                    L.i("uri = " + uri.toString() + " path=" + tmpPath);
                    tmpItem.pic_path_list.add(tmpPath);
                    // guiseAdapter.notifyDataSetChanged();
                    break;

                case FROM_PIC_VIEWPAGER:// 图片浏览
                    tmpItem.pic_path_list = data.getStringArrayListExtra("pic_path_list");
                    // guiseAdapter.notifyDataSetChanged();
                    break;

            }
            interiorAdapter.notifyDataSetChanged();

        }

    }
}
